package com.zt.weibo.utils;

import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Parcelable;

import com.zt.weibo.R;
import com.zt.weibo.login.LoginActivity;

/**
 * 杂七杂八的工具类
 * 
 * @author zhaotong
 */
public class Utilities
{
	/**
	 * 创建一个桌面快捷方式
	 * @param app Application
	 */
	public static void createShortCut(Application app)
	{
		if (hasShortcut(app))
		{
			return;
		}
		Intent addShortCut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
		Parcelable icon = Intent.ShortcutIconResource.fromContext(app, R.drawable.icon);
		addShortCut.putExtra("duplicate", false);
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		intent.setComponent(new ComponentName(app, LoginActivity.class));
		addShortCut.putExtra(Intent.EXTRA_SHORTCUT_NAME, app.getString(R.string.app_name));
		addShortCut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
		addShortCut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
		app.sendBroadcast(addShortCut);
		SharedPreferences mSp = app.getSharedPreferences("ShortCut", Context.MODE_PRIVATE);
		mSp.edit().putBoolean("bIsHas", true).commit();
		
	}

	/**
	 * 判断当前是否存在快捷方式
	 * @param app Application
	 * @return true/false
	 */
	private static boolean hasShortcut(Application app)
	{
		boolean bIsInstallShortcut = false;
		Uri CONTENT_URI = Uri.parse("content://com.android.launcher.settings/favorites?notify=true");
		Cursor c = app.getContentResolver().query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?",
				new String[] { app.getString(R.string.app_name).trim() }, null);
		if (c != null && c.getCount() > 0)
		{
			bIsInstallShortcut = true;
			c.close();
		}
		if (c == null && !bIsInstallShortcut)
		{
			SharedPreferences mSp = app.getSharedPreferences("ShortCut", Context.MODE_PRIVATE);
			bIsInstallShortcut = mSp.getBoolean("bIsHas", false);
		}
		return bIsInstallShortcut;
	}
}
